package service

import (
	"192.168.1.75/go-pkg/helper"
	"192.168.1.75/go-pkg/logx"
	"context"
	"errors"
	"github.com/samber/lo"
	"mini-app/config/mysql"
	"mini-app/internal/dao"
	"mini-app/internal/models"
	"strconv"
	"strings"
)

type PuppetUser struct {
	tbPuppetUser dao.PuppetUserRepo
}

func (t PuppetUser) Create(
	ctx context.Context,
	item *models.PuppetUser,
) error {
	err := dao.NewPuppetUserRepo(ctx).Insert(ctx, item)
	if err != nil {
		logx.Error(ctx, "PuppetUser.Create", logx.Any("err", err))
		return errors.Join(errors.New("创建失败"), err)
	}
	return nil
}

func (t PuppetUser) Update(
	ctx context.Context,
	item *models.PuppetUser,
) error {
	err := dao.NewPuppetUserRepo(ctx).UpdateById(ctx, item)
	if err != nil {
		logx.Error(ctx, "PuppetUser.Update", logx.Any("err", err))
		return errors.Join(errors.New("更新失败"), err)
	}
	return nil
}

func (t PuppetUser) List(
	ctx context.Context,
	page *helper.PageInfo,
	filter dao.PuppetUserListFilter,
) ([]*models.PuppetUser, int64, error) {
	list, total, err := dao.NewPuppetUserRepo(ctx).ListByFilter(ctx, &filter, page)
	if err != nil {
		logx.Error(ctx, "PuppetUser.Update", logx.Any("err", err))
		return nil, 0, errors.Join(errors.New("查询列表失败"), err)
	}
	return list, total, nil
}

func (t PuppetUser) Detail(
	ctx context.Context,
	filter dao.PuppetUserFilter,
) (record *models.PuppetUser, err error) {

	record, err = dao.NewPuppetUserRepo(ctx).FindOneByFilter(ctx, &filter)
	if err != nil {
		logx.Error(ctx, "PuppetUser.Detail", logx.Any("err", err))
		return nil, errors.Join(errors.New("查询失败"), err)
	}

	return record, nil
}

func (t PuppetUser) DeleteById(
	ctx context.Context,
	id int64,
) (err error) {

	err = dao.NewPuppetUserRepo(ctx).DeleteById(ctx, id)
	if err != nil {
		logx.Error(ctx, "PuppetUser.Detail", logx.Any("err", err))
		return errors.Join(errors.New("删除失败"), err)
	}

	return nil
}

func (t PuppetUser) ListRandomPuppetUser(
	ctx context.Context,
	activityId string,
	num int,
) ([]*models.PuppetUser, int64, error) {
	onlineEvent := dao.OnlineEvent{}.Detail(ctx, mysql.NewDB(), activityId)
	if onlineEvent == nil {
		return nil, 0, errors.New("活动不存在")
	}
	excludeUserIds := strings.Split(onlineEvent.SelectedPuppetUser, ",")
	excludeUserIdsInt64 := lo.Map(excludeUserIds, func(item string, _ int) int64 {
		id, _err := strconv.ParseInt(item, 10, 64)
		if _err != nil {
			logx.Error(ctx, "parse user id error", logx.Any("err", _err))
			return 0
		}
		return id
	})

	filter := dao.PuppetUserListFilter{
		ExcludedIDs: excludeUserIdsInt64,
	}
	page := helper.NewPageInfo(int64(1), int64(3000), nil)

	resultList, total, err := t.List(ctx, page, filter)
	if err != nil {
		return nil, 0, err
	}

	resultList = lo.Samples(resultList, num)
	for _, record := range resultList {
		record.WinCount = int(dao.OnlineEventUser{}.WinCount(ctx, mysql.NewDB(), helper.Int64ToString(record.ID)))
	}

	return resultList, total, nil
}
